package com.ljkj.cordial.chat.presenter;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.log.Logger;
import com.lanjiu.lib.utils.sp.SPKeys;
import com.lanjiu.lib.utils.sp.SharedPreferenceHelper;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.plugins.receiver.HeadsetPlugReceiver;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.nic.view.widget.CircleImageView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 语音
 */
public class VoicePresenter extends AChatPresenter {

    private AudioManager am;

    public VoicePresenter(int direction) {
        super(direction);
//        LayoutInflater.from(view.getContext()).inflate(R.layout.item_chat_right_voice, null);
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        if (getDirection() == LEFT) {
            return new ViewLeftHolder(view);
        }
        return new ViewRightHolder(view);
    }

    @Override
    public void bindViewHolder(RecyclerView.ViewHolder holder, Object obj, int position) {
        ChatTableUnit item = (ChatTableUnit) obj;
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            RelativeLayout.LayoutParams paramsCorner = (RelativeLayout.LayoutParams) viewLeftHolder.ivMsgCorner.getLayoutParams();
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewLeftHolder.llVoiceMsg.getLayoutParams();
            Context context = viewLeftHolder.llVoiceMsg.getContext();
            if (am == null && context != null)
                am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (getChatType() == Canstants.SINGLE_CHAT) {
                viewLeftHolder.tvTitle.setVisibility(View.GONE);
                params.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_8);
                paramsCorner.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_20);
            } else {
                viewLeftHolder.tvTitle.setText(TextUtils.isEmpty(item.getAlias()) ? item.getTargetName() : item.getAlias());
            }

            if (item.getVoiceListen() == ChatTableUnit.LISTENED) {
                viewLeftHolder.tvIsRead.setVisibility(View.GONE);
            } else {
                viewLeftHolder.tvIsRead.setVisibility(View.VISIBLE);
            }
            setVisible(viewLeftHolder.cb, item.isVisible());
            setCheck(viewLeftHolder.cb, item.isChecked());
            viewLeftHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            final String path = item.getThumbPath();
            long duration = parseLong(item.getChatAvatarId());
            setLayoutWidthByTime(viewLeftHolder.llVoiceMsg, duration);
            viewLeftHolder.tvVoiceTime.setText(AlbumManageUtil.generateTime(duration));
            viewLeftHolder.llVoiceMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onVoiceListener != null) {
                        onVoiceListener.onItemClick();
                    }
                    viewLeftHolder.tvIsRead.setVisibility(View.GONE);
                    boolean isMac = checkVoicePlayModel(context);
                    int isCurrentListen = item.getVoiceListen();
                    AlbumManageUtil.getInstance().playVoice(path, isMac, new AlbumManageUtil.OnPlayAnimListener() {
                        @Override
                        public void onStartAnim() {
                            AlbumManageUtil.getInstance().animStartVoice(viewLeftHolder.ivVoice, true);
                        }

                        @Override
                        public void onStopAnim() {
                            AlbumManageUtil.getInstance().animStopVoice(viewLeftHolder.ivVoice, true);
                            initVolumeControlStream(context);
                            if (hasUnreadVoiceChat(position + 1, isCurrentListen)) {
                                playNextUnreadVoiceChat(position + 1);
                            }
                        }
                    });
                    item.setVoiceListen(ChatTableUnit.LISTENED);
                    ChatTableBean.update(ChatTableBean.getTableFromId(String.valueOf(item.getId())));
                }
            });

            viewLeftHolder.llVoiceMsg.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            viewLeftHolder.ivIsVisitor.setVisibility(IMSContacts.UserType.TOURISTS_USER.equals(item.getTargetType()) ? View.VISIBLE : View.GONE);
            loadAvatar(item, viewLeftHolder.ivAvatar);
            if (item.getVoiceListen() == ChatTableUnit.LISTENED) {
                viewLeftHolder.tvIsRead.setVisibility(View.GONE);
            } else {
                viewLeftHolder.tvIsRead.setVisibility(View.VISIBLE);
            }
            setReadFinishState(viewLeftHolder.tvDownTime, item.isStartReadFinish());
        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            setVisible(viewRightHolder.cb, item.isVisible());
            Context context = viewRightHolder.llVoiceMsg.getContext();
            if (am == null && context != null)
                am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (item.isVisible()) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.addRule(RelativeLayout.LEFT_OF, viewRightHolder.cb.getId());
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_48);
            } else {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_16);
            }
            setCheck(viewRightHolder.cb, item.isChecked());
            viewRightHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });
            viewRightHolder.ivFail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemReloadClick(v, item, position);
                    }
                }
            });
            final String path = item.getThumbPath();
            long duration = parseLong(item.getChatAvatarId());
            setLayoutWidthByTime(viewRightHolder.llVoiceMsg, duration);
            viewRightHolder.tvVoiceTime.setText(AlbumManageUtil.generateTime(duration));
            viewRightHolder.llVoiceMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isMac = checkVoicePlayModel(context);
                    AlbumManageUtil.getInstance().playVoice(path, isMac, new AlbumManageUtil.OnPlayAnimListener() {
                        @Override
                        public void onStartAnim() {
                            AlbumManageUtil.getInstance().animStartVoice(viewRightHolder.ivVoice, false);
                        }

                        @Override
                        public void onStopAnim() {
                            AlbumManageUtil.getInstance().animStopVoice(viewRightHolder.ivVoice, false);
                            initVolumeControlStream(context);
                        }
                    });
                }
            });

            viewRightHolder.llVoiceMsg.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            loadAvatar(item, viewRightHolder.ivAvatar);
            refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivFail, viewRightHolder.tvDownTime);

        }

    }

    /**
     * 计算布局宽度
     *
     * @param viewGroup
     * @param duration
     */
    public void setLayoutWidthByTime(ViewGroup viewGroup, long duration) {
        ViewGroup.LayoutParams params = viewGroup.getLayoutParams();
        DisplayMetrics display = viewGroup.getContext().getResources().getDisplayMetrics();
        int dp31 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64, display);
        int dp8 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, display);
        long seconds = duration / 1000;
        seconds=seconds<1L?1L:seconds;
        if (seconds >= 2 && seconds < 10) {
            dp31 += (int) (dp8 * (seconds - 1));
        } else if (seconds >= 10) {
            dp31 += (int) (dp8 * 10 + ((seconds - 10) / 10) * dp8);
        } else if (seconds >= 60) {
            dp31 = dp31 + dp8 * 10 + ((60 - 10) / 10) * dp8;
        }
        params.width = dp31;
    }

    @Override
    public void bindViewHolder(ChatAdapter chatAdapter, int position, RecyclerView.ViewHolder holder, Object obj, PayLoad payLoad) {
        super.bindViewHolder(chatAdapter, position, holder, obj, payLoad);
        ChatTableUnit item = (ChatTableUnit) obj;
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewLeftHolder.ivAvatar);
                if (PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish()) {
                        viewLeftHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
            }

        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewRightHolder.ivAvatar);
                if (item.getSendState() == ChatTableUnit.SEND_SUCCESS && PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish() && item.getSendState() == ChatTableUnit.SEND_SUCCESS) {
                        viewRightHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
                if (PayLoad.REQ_STATE == type) {
                    refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivFail, viewRightHolder.tvDownTime);
                }
            }
        }

    }


    public static class ViewLeftHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.iv_is_visitor)
        ImageView ivIsVisitor;
        @BindView(R.id.ll_avatar)
        FrameLayout llAvatar;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.iv_voice)
        ImageView ivVoice;
        @BindView(R.id.tv_voice_time)
        TextView tvVoiceTime;
        @BindView(R.id.ll_voice_msg)
        LinearLayout llVoiceMsg;
        @BindView(R.id.tv_is_read)
        TextView tvIsRead;
        @BindView(R.id.iv_msg_corner)
        ImageView ivMsgCorner;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewLeftHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            setIsRecyclable(false);
        }
    }

    public static class ViewRightHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.tv_voice_time)
        TextView tvVoiceTime;
        @BindView(R.id.iv_voice)
        ImageView ivVoice;
        @BindView(R.id.ll_voice_msg)
        LinearLayout llVoiceMsg;
        @BindView(R.id.iv_fail)
        ImageView ivFail;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewRightHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
            setIsRecyclable(false);
        }
    }

    private OnVoiceListener onVoiceListener;

    public void setOnVoiceListener(OnVoiceListener onVoiceListener) {
        this.onVoiceListener = onVoiceListener;
    }

    public interface OnVoiceListener {
        void onItemClick();
    }

    private void initVolumeControlStream(Context context) {
        if (context instanceof Activity) {
            ((Activity) context).setVolumeControlStream(AudioManager.STREAM_RING);
        }
        if (am != null) {
            am.stopBluetoothSco();
            am.setBluetoothScoOn(false);
            am.setSpeakerphoneOn(true);
            am.setMode(AudioManager.MODE_NORMAL);
        }
    }

    private boolean checkVoicePlayModel(Context context) {
        String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
        boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
        if (context instanceof Activity) {
            ((Activity) context).setVolumeControlStream(isMac ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC);
        }
        if (am != null) {
            if (HeadsetPlugReceiver.isIsBluetoothHeadset()) {
                am.startBluetoothSco();
                am.setBluetoothScoOn(true);
                am.setSpeakerphoneOn(false);
            } else {
                am.stopBluetoothSco();
                am.setBluetoothScoOn(false);
                am.setSpeakerphoneOn(!isMac);
            }
            am.setMode(getAudioManagerMode(isMac));
        }
        return isMac;

//        if (HeadsetPlugReceiver.isHeadset()) {
//            if (context instanceof Activity) {
//                ((Activity) context).setVolumeControlStream(AudioManager.STREAM_MUSIC);
//            }
//            if (am != null) {
//                am.setSpeakerphoneOn(true);
//                am.setMode(AudioManager.MODE_NORMAL);
//            }
//            return false;
//        } else {
//            if (context instanceof Activity) {
//                ((Activity) context).setVolumeControlStream(isMac ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC);
//            }
//            if (am != null) {
//                am.setSpeakerphoneOn(!isMac);
//                am.setMode(getAudioManagerMode(isMac));
//            }
//            return isMac;
//        }
    }

    public int getAudioManagerMode(boolean isMac) {
        if (isMac) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                return AudioManager.MODE_IN_COMMUNICATION;
            } else {
                return AudioManager.MODE_IN_CALL;
            }
        } else {
            return HeadsetPlugReceiver.isIsBluetoothHeadset() ? AudioManager.MODE_IN_COMMUNICATION : AudioManager.MODE_NORMAL;
        }
    }

    public void playNextUnreadVoiceChat(int position) {
        RecyclerView recyclerView = getRecyclerView();
        if (recyclerView != null && recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            try {
                for (int i = position; i < getDataSet().size(); i++) {
                    ChatTableUnit ChatTableUnit = getDataSet().get(i);
                    if (ChatTableUnit.getSendType() == ChatTableUnit.RECEIVE &&
                            ChatTableUnit.getChatType() == MsgType.Voice &&
                            ChatTableUnit.getVoiceListen() == ChatTableUnit.UNLISTEN) {
                        int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                        boolean isScroll = false;
                        if (i >= lastCompletelyVisibleItemPosition - 1) {
                            // 倒数第二条的时候要开始滚动屏幕了
                            int firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
                            layoutManager.scrollToPositionWithOffset(firstCompletelyVisibleItemPosition + 1, 0);
                            isScroll = true;
                        }
                        final int finalI = i;
                        recyclerView.postDelayed(() -> {
                            View viewByPosition = layoutManager.findViewByPosition(finalI);
                            if (viewByPosition == null)
                                viewByPosition = recyclerView.getChildAt(finalI);
                            if (viewByPosition != null) {
                                RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(viewByPosition);
                                if (viewHolder instanceof ViewLeftHolder) {
                                    ((ViewLeftHolder) viewHolder).llVoiceMsg.performClick();
                                }
                            }
                        }, isScroll ? 500 : 50);
                        break;
                    }
                }
            } catch (Exception e) {
                Logger.print("============================>连续播放异常");
            }
        }
    }

    public boolean hasUnreadVoiceChat(int position, int isCurrentRead) {
        if (getDataSet() != null && position >= 0 && position < getDataSet().size()) {
            for (int i = position; i < getDataSet().size(); i++) {
                ChatTableUnit t = getDataSet().get(i);
                if (isCurrentRead == ChatTableUnit.LISTENED) {
                    return false;
                } else {
                    if (t.getSendType() == ChatTableUnit.RECEIVE && t.getChatType() == MsgType.Voice && t.getVoiceListen() == ChatTableUnit.UNLISTEN) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public long parseLong(String du) {
        try {
            return Long.parseLong(du);
        } catch (NumberFormatException e) {
            return 0L;
        }
    }
}
